import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userRole: localStorage.getItem('userRole') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
  }),

  getters: {
    isAuthenticated: (state) => !!state.token,
    getUserRole: (state) => state.userRole,
    getUserInfo: (state) => state.userInfo
  },

  actions: {
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },
    setUserRole(role) {
      this.userRole = role
      localStorage.setItem('userRole', role)
    },
    setUserInfo(info) {
      this.userInfo = info
      localStorage.setItem('userInfo', JSON.stringify(info))
    },
    login({ token, role, userInfo }) {
      this.setToken(token)
      this.setUserRole(role)
      if (userInfo) {
        // 确保userInfo中包含role字段
        let updatedUserInfo = {
          ...userInfo,
          role: role
        }
        
        // 处理devices字段，确保它是一个正确的设备ID数组
        if (updatedUserInfo.devices) {
          // 如果devices是一个数组，但只包含一个逗号分隔的字符串
          if (Array.isArray(updatedUserInfo.devices) && updatedUserInfo.devices.length === 1 && typeof updatedUserInfo.devices[0] === 'string' && updatedUserInfo.devices[0].includes(',')) {
            // 将逗号分隔的字符串拆分为单独的设备ID数组
            updatedUserInfo.devices = updatedUserInfo.devices[0].split(',').map(id => id.trim())
          }
        }
        
        this.setUserInfo(updatedUserInfo)
      }
    },
    logout() {
      this.token = ''
      this.userRole = ''
      this.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userRole')
      localStorage.removeItem('userInfo')
    },
    checkAuth() {
      const token = localStorage.getItem('token')
      const role = localStorage.getItem('userRole')
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      if (token) {
        this.token = token
        this.userRole = role
        this.userInfo = userInfo
        return true
      }
      return false
    }
  }
})